package service

import (
	"golang.org/x/net/websocket"

	"github.com/nsqio/go-nsq"
	"kingbloc.util/util"
	"log"
)

var Wss *websocket.Conn

func InitConsumer(addrAndPort, channel, topic string) {
	c, err := nsq.NewConsumer(topic, channel, nsq.NewConfig()) // 新建一个消费者
	util.CheckErr(err)
	c.AddHandler(&ConsumerT{}) // 添加消息处理
	//	if errA := c.ConnectToNSQLookupd("http://127.0.0.1:4161"); errA != nil {
	//	if err := c.ConnectToNSQD("127.0.0.1:4150"); err != nil { // 建立连接
	err = c.ConnectToNSQD(addrAndPort)
	util.CheckErr(err)

}

// nsq订阅消息
type ConsumerT struct{}

func (*ConsumerT) HandleMessage(msg *nsq.Message) error {

	if Wss != nil {
		err := websocket.Message.Send(Wss, string(msg.Body))
		util.CheckErr(err)
	}
	return nil
}

func Echo(ws *websocket.Conn) {

	Wss = ws
	cookie, err := ws.Request().Cookie("SSOTOKEN")
	util.CheckErr(err)
	log.Fatal(cookie)

	for {
		var reply string
		err := websocket.Message.Receive(ws, &reply)
		util.CheckErr(err)

		if reply != "" {
			msg := &Msg{Topic: "test", Method: "", Data: reply}
			Publish(msg)
		}
	}
}
